package commander;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;


import CommitLink.CommitLink;
import Index.Index;
import core.*;
import gitobject.Commit;
import repository.Repository;


/**
 * 实现与用户的交互，调用core之中的具体方法实现用户需要的功能
 */
public class CLI {
	/**
	 * 判断传入路径是绝对路径还是相对路径
	 * @param path
	 * @return
	 */
	public static boolean isAbsolutePath(String path) {
		if (path.startsWith("/") || path.indexOf(":") > 0) {
			return true;
		}
		return false;
	}

	/**
	 * Command 'jit init'
	 * @param args
	 * @throws IOException
	 */
	public static void jitInit(String[] args) throws IOException {
		String path = "";
		if(args.length <= 2) { //get default working path
			path = new File(".").getCanonicalPath();
			JitInit.init(path);
		}else if(args[2].equals("-help")){ //see help
			System.out.println("usage: jit init [<path>] [-help]\r\n" +
					"\r\n" +
					"jit init [<path>]:	Create an empty jit repository or reinitialize an existing one in the path or your default working directory.");
		}else {
			path = args[2];
			if(!new File(path).isDirectory()) { //if the working path input is illegal
				System.out.println(path + "is not a legal directory. Please init your reposiroty again. See 'jit init -help'.");
			}else {
				JitInit.init(path);
			}
		}
	}
	

	/**
	 * Command 'jit help'.
	 */
	public static void jitHelp() {
		System.out.println("usage: jit [--version] [--help] [-C <path>] [-c name=value]\r\n" +
				"           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]\r\n" +
				"           [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]\r\n" +
				"           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]\r\n" +
				"           <command> [<args>]\r\n" +
				"\r\n" +
				"These are common Jit commands used in various situations:\r\n" +
				"\r\n" +
				"start a working area\r\n" +
				"   init       Create an empty Jit repository or reinitialize an existing one\r\n" +
				"\r\n" +
				"work on the current change\r\n" +
				"   add        Add file contents to the index\r\n" +
				"   reset      Reset current HEAD to the specified state\r\n" +
				"   rm         Remove files from the working tree and from the index\r\n" +
				"\r\n" +
				"examine the history and state\r\n" +
				"   log        Show commit logs\r\n" +
				"   status     Show the working tree status\r\n" +
				"\r\n" +
				"grow, mark and tweak your common history\r\n" +
				"   branch     List, create, or delete branches\r\n" +
				"   checkout   Switch branches or restore working tree files\r\n" +
				"   commit     Record changes to the repository\r\n" +
				"   diff       Show changes between commits, commit and working tree, etc\r\n" +
				"   merge      Join two or more development histories together\r\n" +
				"\r\n" +
				"'jit help -a' and 'jit help -g' list available subcommands and some\r\n" +
				"concept guides. See 'jit help <command>' or 'jit help <concept>'\r\n" +
				"to read about a specific subcommand or concept.");
	}

	/**
	 * Command 'jit add '.
	 */
	public static void jitAdd(String[] args) throws Exception {
		String path;
		if(args.length == 2){
			System.out.println("Nothing specified, nothing added.\n" +
					"\t\t\t\thint: Maybe you wanted to say 'git add .'?\n" +
					"\t\t\t\thint: Turn this message off by running\n" +
					"\t\thint: \"git config advice.addEmptyPathspec false\"");
			return;
		}
		if(args[2] == "."){
			path = new File(".").getCanonicalPath();
			File workArea = new File(path);
			File[] files = workArea.listFiles();
			for(File file: files){
				if(file.getAbsolutePath().contains(".jit")){
					continue;
				}
				JitAdd.add(file.getAbsolutePath());
			}
		}else{
			path = args[2];
			if(!isAbsolutePath(path)){  //判断传入参数是绝对路径还是相对路径
				path = new File(".").getCanonicalPath() + File.separator + args[2];
			}
			JitAdd.add(path);
		}
		Index index = new Index();
		ArrayList<String> arrayList = index.getBlobList();
		System.out.println("暂存区现有" + arrayList.size() + "个文件，分别为：");
		for(String tem: arrayList){
			System.out.println(tem);
		}
	}

	/**
	 * Command 'jit commit'.
	 */
	public static void jitCommit(String[] args) throws Exception {
		if(args[2].startsWith("-m")){
			String message = args[2].substring(2,args[2].length());    //获取提交信息
			JitCommit.commit(message);
		}

	}

	/**
	 * Command 'jit branch'.
	 */
	public static void jitBranch(String[] args) throws Exception {
		if(args.length == 2){
			JitBranch.branch();		//显示当前分支信息
			return;
		}else if(args[1].equals("branch")) {
			if(args[2].equals("-d")){		//删除分支
				JitBranch.deleteBranch(args[3]);
			}else {
				JitBranch.branch(args[2]);
				System.out.println("branch " + args[2] + " has been created");
			}
		}else if(args[1].equals("checkout")){	//切换分支
			JitBranch.checkout(args[2]);
			System.out.println("Switched to branch " + args[2] +" successfully.");
		}
	}

	/**
	 * Command 'jit rm'.
	 */
	public static void jitRm(String[] args) throws Exception {
		String path = args[2];
		if(!isAbsolutePath(args[2])){
			path = new File(".").getCanonicalPath() + File.separator + args[2];
		}
		JitRm.remove_cached(path);
	}

	/**
	 * Command 'jit reset'.
	 */
	public static void jitReset(String[] args) throws Exception {
		if(args[2].equals("--soft")){
			JitReset.reset_soft(args[3]);
		}else if(args[2].equals("--mixed")){
			JitReset.reset_mid(args[3]);
		}else if(args[2].equals("--hard")){
			JitReset.reset_hard(args[3]);
		}
	}

	/**
	 * Command 'jit log'.
	 */
	public static void jitLog() throws IOException {
		CommitLink commitLink = new CommitLink();
		commitLink.readObject().getCommitList().display();
	}

	
	public static void main(String[] args) throws Exception {

			if (args.length <= 1 || args[1].equals("help")) {
				jitHelp();
			} else if (args[1].equals("init")) {
				jitInit(args);
			} else if (args[1].equals("add")) {
				jitAdd(args);
			} else if (args[1].equals("commit")) {
				jitCommit(args);
			} else if (args[1].equals("branch")) {
				jitBranch(args);
			} else if (args[1].equals("rm")) {
				jitRm(args);
			} else if (args[1].equals("reset")) {
				jitReset(args);
			} else if (args[1].equals("log")) {
				jitLog();
			} else if (args[1].equals("checkout")){
				jitBranch(args);
			}
			else {
				System.out.println("jit: " + args[1] + "is not a jit command. See 'git help'.");
			}
	}
}
